﻿using Microsoft.EntityFrameworkCore;
using Project.Core.Config.Entity;
using System.Diagnostics;
using System.Reflection;

namespace Project.Core.Config.Config.DbConnect
{
    public class AppDbContext : DbContext
    {

        private readonly string?[] _assemblyNames;
        public AppDbContext(DbContextOptions<AppDbContext> options, string?[] assemblyNames) : base(options)
        {
            _assemblyNames = assemblyNames;
        }

        //public DbSet<Book> book { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);

            //optionsBuilder.LogTo(msg => {
            //    if (!msg.Contains("CommandExecuted")) return;
            //    Debug.WriteLine(msg);
            //});
        }

        //动态创建DbSet
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            var assemblies = _assemblyNames.Select(x => Assembly.Load(x)).ToList();
            //assemblies.Add(Assembly.GetExecutingAssembly());

            foreach (var assembly in assemblies)
            {
                foreach (Type type in assembly.ExportedTypes)
                {
                    if (type.IsClass &&
                        (type != typeof(BaseEntity<int>) && typeof(BaseEntity<int>).IsAssignableFrom(type)) ||
                        (type != typeof(BaseEntity<long>) && typeof(BaseEntity<long>).IsAssignableFrom(type)))
                    {
                        var method = modelBuilder.GetType().GetMethods().Where(x => x.Name == "Entity").FirstOrDefault();

                        if (method != null)
                        {
                            method = method.MakeGenericMethod(new Type[] { type });
                            method.Invoke(modelBuilder, null);
                        }
                    }
                }
            }

            base.OnModelCreating(modelBuilder);
        }
    }
}
